package com.wjp.dinosaur.service.impl;

import com.google.common.collect.Maps;
import com.wjp.dinosaur.dao.mapper.UserMapper;
import com.wjp.dinosaur.dao.pojo.User;
import com.wjp.dinosaur.service.ScoreService;
import com.wjp.dinosaur.util.UserIdUtil;
import com.wjp.dinosaur.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.function.ToIntFunction;

@Service
public class ScoreImpl implements ScoreService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public Result getScore() {
        Set<String> keys = redisTemplate.keys("ACCOUNT_".concat("*"));
        HashMap<String, String> map = new HashMap<>();

        for (String iterator:keys){
            String id = iterator.substring(8);
            User user = userMapper.selectById(Long.parseLong(id));
            String score = redisTemplate.opsForValue().get(iterator);
            map.put(user.getUserName(),score);
        }
        List<HashMap<String, String>> entries = sortMap(map);
        return Result.success(entries);
    }

    @Override
    public Result getMe() {
        // 获取设置用户自己的内容
        Long userId = UserIdUtil.getUserId(request);
        String score = redisTemplate.opsForValue().get("ACCOUNT_" + userId);
        HashMap<String, String> me = new HashMap<>();
        me.put("me",score);
        return Result.success(me);
    }

    public List<HashMap<String, String>> sortMap(HashMap map){
        List<Map.Entry<String,String>> mappingList = null;
        //通过ArrayList构造函数把map.entrySet()转换成list
        mappingList = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        //通过比较器实现比较排序
        Collections.sort(mappingList, new Comparator<Map.Entry<String,String>>(){
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return Integer.parseInt(o1.getValue())-Integer.parseInt(o2.getValue());
            }
        });
        List<HashMap<String, String>> mappingList2 = new ArrayList<HashMap<String, String>>();
        for (int i = 0; i < mappingList.size() && i<10; i++){
            HashMap<String, String> map1 = new HashMap<String, String>();
            map1.put("name",mappingList.get(i).getKey());
            map1.put("grade",mappingList.get(i).getValue());
            mappingList2.add(map1);
        }
        return mappingList2;
    }

}
